<template>
  <div class="menu-create">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑广告位' : '添加广告位' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="广告位名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button
            v-if="!isEdit"
            @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { createOrUpdateAdvertSpace, getAdvertSpaceInfo } from '@/services/advert'

export default Vue.extend({
  name: 'advertSpaceCreateOrEdit',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入广告名称', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    if (this.isEdit) {
      this.loadAdvertInfo()
    }
  },

  methods: {
    async loadAdvertInfo () {
      const { data } = await getAdvertSpaceInfo({ id: this.$route.params.id })
      this.form = data.content
    },

    onReset () {
      (this.$refs.form as Form).resetFields()
    },

    async onSubmit () {
      // 1. 表单验证
      // 2. 验证通过，提交表单
      (this.$refs.form as Form).validate(async (valid: any) => {
        if (valid) {
          const { data } = await createOrUpdateAdvertSpace(this.form)
          if (data.success) {
            this.$message.success('提交成功')
            this.$router.back()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
})
</script>

<style lang="scss" scoped></style>
